import React, { useEffect, useState } from "react"
import { getCustomerData, customerRenew, customerCheckOut, getCurrentDate, DateDiff } from '@/request/api'
import type { ColumnsType } from 'antd/es/table'
import type { DatePickerProps } from 'antd'
import { Table, Button, Modal, DatePicker, message, Popconfirm, Input } from 'antd'
import styles from './customer.module.scss'
const { Search } = Input;


const CustomerView: React.FC = () => {

  const [customerData, setCustomerData] = useState([])
  const [customer, setCustomer] = useState<CustomerType>()
  const [totle, setTotle] = useState(1)
  const [pageSize] = useState(7) //分页条数
  const [isModalOpen, setIsModalOpen] = useState(false) //控制弹窗
  const [renewDate, setRenewDate] = useState("") //控制弹窗
  const [temp, setTemp] = useState("") //搜索

  useEffect(() => {
    getData()
  }, [])

  //确认退房
  const confirm = async () => {
    if (customer) {
      const time = new Date()
      const params: checkOutRes = {
        beginDate: customer.beginDate,
        endDate: customer.endDate, 
        roomId:customer.roomId,
        createdDate: getCurrentDate(time.toLocaleString('en-US', { hour12: false }).split(" ")), 
        customerCardId: customer.cardId, 
        customerId: customer?.id, 
        customerName: customer.name,
        customerPhone: customer.phone, 
        totalAmount: customer.roomPrice * DateDiff(customer.endDate, customer.beginDate), 
        operator: localStorage.getItem('token') as string,
      }

      const {code} = await customerCheckOut(params)
      if (code == 0) {
        getData()
        message.success({ content: "退房成功！", duration: 5 })
      }
    }
  };

  const checkOut = (customer: CustomerType) => {
    setCustomer(customer)
  }

  const columns: ColumnsType<CustomerType> = [
    {
      title: '编号',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '电话',
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title: '身份证号码',
      key: 'cardId',
      dataIndex: 'cardId',
    },
    {
      title: '入住时间',
      key: 'beginDate',
      dataIndex: 'beginDate',
    },
    {
      title: '退房时间',
      key: 'endDate',
      dataIndex: 'endDate',
    },
    {
      title: '房号',
      key: 'roomId',
      dataIndex: 'roomId',
    },
    {
      title: '房间单价',
      key: 'roomPrice',
      dataIndex: 'roomPrice',
    },
    {
      title: '总价',
      key: 'totalAmount',
      dataIndex: 'totalAmount',
      render: (_, record) => {
        return (
          <>
            {record.roomPrice * DateDiff(record.endDate, record.beginDate)}
          </>
        )
      }
    },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (_, record) => {
        return (
          <>
            <Popconfirm
              title="退房提示"
              description="确认该用户要退房吗？"
              onConfirm={confirm}
              okText="Yes"
              cancelText="No"
            >
              <Button type="primary" size='small' style={{ marginRight: '5px' }} onClick={() => checkOut(record)}>退房</Button>
            </Popconfirm>
            
            <Button type="primary" size='small' onClick={() => renew(record)}>续住</Button>
          </>
        )
      }
    }
  ];
  

  const renew = (customer: CustomerType) => {
    setCustomer(customer)
    setIsModalOpen(true)
  }


  const getData = async (pageNum: number = 1, search:string = "") => {
    const { data, code } = await getCustomerData({ pageNum, pageSize, search })

    if (code == 0) {
      setTotle(data.total)
      setCustomerData(data.records)
    }
  }

  const renewSumbit =  async () => {
    if (customer) {
      const { data, code } = await customerRenew({ ...customer, endDate: renewDate })
      if (code == 0) {
        message.success({ content: data, duration: 3 })
        getData()
      }
    }
   
    setIsModalOpen(false)
  }

  const onChange: DatePickerProps['onChange'] = (_date, dateString) => {
    setRenewDate(dateString)
    getData()
  }

  const onSearch = (value:string) => {
    setTemp(value)
    getData(1, value)
  } 

  return (
    <>
      <div style={{width: '300px', margin: '20px 20px 20px 0'}}>
        <Search placeholder="请输入预定的客户姓名" onSearch={onSearch} enterButton allowClear/>
      </div>
      <Table columns={columns} dataSource={customerData} rowKey="id" pagination={
        {
          total: totle,//数据的总条数
          defaultCurrent: 1,//默认当前的页数
          defaultPageSize: pageSize,//默认每页的条数
          onChange: (page: number) => getData(page, temp)
        }
      } />

      <Modal title={"客户续住：" + customer?.name + "---" + customer?.roomId} open={isModalOpen} footer={null} onCancel={() => setIsModalOpen(false)}>
        <div className={styles.renewModal}>
          <div className={styles.text}>续住日期：</div>
          <DatePicker onChange={onChange} />
        </div>
        <div style={{textAlign: 'right'}}><Button onClick={renewSumbit} type="primary" size='small'>确定</Button></div>
      </Modal>
    </>
  )
}

export default CustomerView